#include "mainwidget.h"

mainWidget::mainWidget(QWidget *parent)
    : QWidget(parent)
{
    setWindowTitle(tr("TCP Server"));

    ContentListWidegt = new QListWidget;
    PortLabel = new QLabel(tr("Port:"));
    PortLineEdit = new QLineEdit;
    PortLineEdit->setInputMask("9999");
    CreateBtn = new QPushButton(tr("Create Room"));
    QuitBtn = new QPushButton(tr("Quit Room"));
    CloseBtn = new QPushButton(tr("Close"));

    //布局
    mainLayout = new QGridLayout(this);
    mainLayout->addWidget(ContentListWidegt, 0, 0, 1, 2);
    mainLayout->addWidget(PortLabel, 1, 0);
    mainLayout->addWidget(PortLineEdit, 1, 1);
    mainLayout->addWidget(CreateBtn, 2, 0);
    mainLayout->addWidget(QuitBtn, 2, 1);
    mainLayout->addWidget(CloseBtn, 3, 0, 1, 2);

    port = 8888;
    PortLineEdit->setText(QString::number(port));
    connect(CreateBtn, SIGNAL(clicked()), this, SLOT(slotCreateServer()));
    connect(QuitBtn, SIGNAL(clicked()), this, SLOT(slotQuit()));
    connect(CloseBtn, SIGNAL(clicked()), this, SLOT(slotClose()));
    CreateBtn->setEnabled(true);
    QuitBtn->setEnabled(false);
    CloseBtn->setEnabled(true);
}

mainWidget::~mainWidget()
{
}

void mainWidget::slotCreateServer()
{
    server = new TcpServer(this, port);
    connect(server, SIGNAL(updateServer(QString, int)), this, SLOT(updateServer(QString, int)));
    CreateBtn->setEnabled(false);
    QuitBtn->setEnabled(true);
}

void mainWidget::updateServer(QString msg, int length)
{
    ContentListWidegt->addItem(msg.left(length));
}

void mainWidget::slotQuit()
{
    server->close();
    CreateBtn->setEnabled(true);
}

void mainWidget::slotClose()
{
    close();
}
